package com.meilai.project.dto.base;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xchen
 * @since 2022-01-23
 */

@Data
@ApiModel
public class PageReq {
    @ApiModelProperty(value = "当前页", required = true)
    private Integer page;
    @ApiModelProperty(value = "每页数量", required = true)
    private Integer page_size;

    /**
     * 排序字段
     */
    @ApiModelProperty(value = "排序字段,多个使用英文逗号分割")
    private String orderFields;


    /**
     * 排序类型，desc/asc
     */
    @ApiModelProperty(value = "排序类型（desc/asc）,和上面的字段一一对应，多个使用英文逗号分开")
    private String orderFieldSort;

    /**
     * 是否查询数量,默认查询数量
     */
    private boolean isSearchCount = true;


    private List<OrderItem> _orderItems;

    /**
     * 必须写在getter上，否则无效
     */
    @ApiModelProperty(hidden = true)
    public boolean isSearchCount() {
        return isSearchCount;
    }

    /**
     * 创建mybatis-plus Page对象
     */
    public <T> Page<T> createPage(Class<T> requireType) {
        Page<T> result = new Page<>(this.page, this.page_size, this.isSearchCount);
        if (StrUtil.isNotEmpty(this.orderFields) && StrUtil.isNotEmpty(this.orderFieldSort)) {
            String[] orderByArr = this.orderFields.split(",");
            String[] orderTypeArr = this.orderFieldSort.split(",");

            for (int i = 0; i < orderByArr.length; ++i) {
                String sortBy = orderByArr[i];
                String sortType = orderTypeArr[i];
                OrderItem orderItem = new OrderItem();
                orderItem.setAsc("asc".equalsIgnoreCase(sortType));
                orderItem.setColumn(sortBy);
                result.addOrder(orderItem);
            }
            if (CollUtil.isNotEmpty(this._orderItems)) {
                result.addOrder(this._orderItems);
            }
        }
        return result;
    }

    public void addOrderItem(String name, boolean asc) {
        if (null == _orderItems) {
            _orderItems = new ArrayList<>();
        }
        OrderItem orderItem = new OrderItem(name, asc);
        _orderItems.add(orderItem);
    }

}
